package cn.qing.controller;

import cn.qing.pojo.Product;
import cn.qing.pojo.Role;
import cn.qing.pojo.UserInfo;
import cn.qing.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 查找user用户
     * @param page
     * @param size
     * @return
     */
    @RolesAllowed("ADMIN") //权限
    @RequestMapping("findAll")
    public ModelAndView method(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "size",defaultValue = "5") Integer size){

        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfoList = userService.findAll(page,size);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfoList);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     * 保存用户
     * @param userInfo
     * @return
     */
    @RequestMapping("save")
    public String save(UserInfo userInfo){
        userService.save(userInfo);
        return "redirect:findAll.do";
    }

    /**
     * 用户详情
     * @param id
     * @return
     */
    @RequestMapping("findById")
    public ModelAndView findById(@RequestParam Integer id){

        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    /**
     * 给用户添加角色
     * @param userId
     * @return
     */
    @RequestMapping("findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(@RequestParam("id") Integer userId){

        ModelAndView mv = new ModelAndView();
        //根据id查询用户信息
        UserInfo userbyId = userService.findById(userId);
        //根据id查寻用户可以添加的角色
        List<Role> roleList = userService.findOtherRoles(userId);

        mv.addObject("user",userbyId);
        mv.addObject("roleList",roleList);
        mv.setViewName("user-role-add");
        return mv;
    }

    /**
     * 保存 给用户添加角色
     * @param userId
     * @param ids
     * @return
     */
    @RequestMapping("addRoleToUser")
    //这个userId就是上面方法的获取的userId，通过jsp在传过来
    public String addRoleToUser(Integer userId,Integer[] ids){

        System.out.println("userId:"+userId);
        for (Integer id : ids){
            System.out.println(id);
        }
        userService.addRoleToUser(userId,ids);
        return "redirect:findAll.do";
    }
}
